#!/Users/hepeng/.pyenv/shims/python
# -*- coding: utf-8 -*-
# @Time    : 2020/3/26 7:50 下午
# @Author  : hepeng
# @Site    : 
# @File    : IniUtils.py

import configparser

import threading

import shutil, os, time


class ConfigHanlder(object):
    _instance_lock = threading.Lock()

    def __init__(self, path):
        self._path = path
        self._conf = configparser.ConfigParser()
        self._conf.read(path, encoding='utf-8')

    def __new__(cls, *args, **kwargs):
        if not hasattr(ConfigHanlder, "_instance"):
            with ConfigHanlder._instance_lock:
                if not hasattr(ConfigHanlder, "_instance"):
                    ConfigHanlder._instance = object.__new__(cls)
        return ConfigHanlder._instance

    def get_val(self, section, key):
        '''
            :param section: 段名
            :param key: key 值
            获取属性值
        '''

        return self._conf.get(section, key)

    def get_dict_by_section(self, section):
        '''
           :param section: 段名
           通过section名称，将该section下的所有配置项转化为字典
        '''
        items = self._conf.items(section)
        return {k: v for k, v in (it for it in items)}

    def get_all_dict(self, section_name=''):
        '''
        获取配置文件所有值，默认为全部
        :param section_name 段名或部分
        :return 字典形式 { secion_name: {k1:v1,k2:v2} }
        '''
        section_list = self._conf.sections()
        return {section: self.get_dict_by_section(section) for section in section_list if section_name in section}

    def bak_file(self, bak_name=None):
        '''
          :param bak_name: 备份文件标示，默认时间戳
          备份文件
        '''
        dir, file_name = os.path.split(self._path)
        if not bak_name:
            bak_name = str(int(time.time()))
        bak_file_path = os.path.join(dir, file_name + '_' + bak_name)
        shutil.copy(self._path, bak_file_path)

    def updata_value(self, section, key, value):
        '''
        根据section, key 更新value值
        :param section:  段名
        :param key:  key值
        :param value:  更新的value
        '''
        self._conf.set(section, key, value)

    def add_section(self, section_name, kv_dict=None):
        '''
        添加 section
        :param section_name: 添加段名
        :param kv_dict:  需要添加在该段下的key 、value 字典
        :return:
        '''
        self._conf.add_section(section_name)
        if not kv_dict:
            return
        for k, v in kv_dict.items():
            self.updata_value(section_name, k, v)

    def has_key(self, section, key):
        return self._conf.has_option(section, key)

    def has_section(self, section):
        return self._conf.has_section(section)

    def remove_key(self, section_name, key):
        '''
        根据section，移除该段下的key
        :param section_name: 段名
        :param key: 被移除key
        '''
        return self._conf.remove_option(section_name, key)

    def remove_section(self, section_name):
        '''
        移除section
        :param section_name: 段名
        :return:
        '''
        return self._conf.remove_section(section_name)

    def write_file(self):
        '''
        写文件
        :return:
        '''
        with open(self._path, 'w+', encoding='utf-8') as f:
            self._conf.write(f)

    def updata_value_plus(self,section_name, kv_dict):
        if not self.has_section(section_name):
            self.add_section(section_name,kv_dict)
        else:
            for k,v in kv_dict:
                self.updata_value(section_name,k,v)

def configWriter(func_or_cls):
    def wrapper(self, *args, **kwargs):
        try:
            func_or_cls(self, *args, **kwargs)
            self._conf.bak_file()
            self._conf.write_file()
        except Exception as  e:
            raise e

    return wrapper


if __name__ == '__main__':
    c = ConfigHanlder('../playbook/dev.ini')
    d= c.get_all_dict()
    c1 = sorted(c.get_all_dict().keys(), key=lambda key: key.rsplit('_', 1))
    print  {cc: d.get(cc) for cc in c1 }

